<?php
class UserServer {
	public function pagingBySearch($where="",$order='',$numberEachPage = 10){
		$count = HttpDaoManager::getUserDao()->searchNumber($where);
		$page = new Page($count, $numberEachPage);
		$limit[0]= $page->which;
		$limit[1]=$numberEachPage;
		$list = HttpDaoManager::getUserDao()->searchList($where,$order, $limit);
		$page1= $page->returnPage("?".ClassManager::getToos()->combinationGet('page')."&page=");
		$data['list'] =$list;
		$data['page'] = $page1;
		return $data;
	}
	public function registerAndLogin($data){
		$domain=strtolower(substr($data['email'],stripos($data['email'],'@')));
		$mail_name = substr($data['email'],0,stripos($data['email'],'@'));
		$data['email']=$mail_name.$domain;
		$tmp =  $this->register($data);
		if ($tmp==true){
			$this->login($data['email'], $data['password']);
		}
		return $tmp;
	}
	
	public function getUserInfo($data){
		$userData = array();
		$user_id = $data['user_id'];
		$sumStudyClass = HttpDaoManager::getBookCourseDao()->searchNumber(array('class_status'=>CLASS_STATUS_2,'user_id'=>$user_id));
		$data['sumStudyClass'] = $sumStudyClass;	
		return $data;
	}
	/**
	 *注册 
	 */
	public function register($data){
		if (empty($data['email'])){
			return ERROR_CODE_ONE;
		}
		if (empty($data['password'])){
			return ERROR_CODE_TWO;
		}
// 		if (empty($data['phone'])){
// 			return ERROR_CODE_THREE;
// 		}
		$userdata = HttpDaoManager::getUserDao()->getByEmail($data['email']);
		if (!empty($userdata)){
			return ERROR_CODE_FOUR;
		}
		
		if(!empty($data['phone'])){
			$userdata = HttpDaoManager::getUserDao()->getByPhone($data['phone']);
			if (!empty($userdata)){
				return ERROR_CODE_FIVE;
			}
		}

		$data['password'] = md5($data['password']);
		$data['register_time']   = time();
		if (isset($data['invitation_user_id'])){
			$data['user_id'] = $data['invitation_user_id'];
		}
		$data['user_type'] = USER_TYPE_NOACTION;
		$data['english_name'] = $data['english_name'];
		if($data['fund_user_id']<0){
			$data['fund_user_id'] = 0;
		}
		HttpDaoManager::getUserDao()->add($data);
		//若是邀请注册成功，准备派送礼品
		if(isset($data['user_id'])&&$data['user_id']>0){
			$this->sendInviteFavour($data['user_id']);//派送礼品		
			setcookie("invitation_user_id", NULL);//清除库存
		}

		return true;
	}
	
	public function sendInviteFavour($user_id){
		 $user_info = HttpDaoManager::getUserDao()->get($user_id);
		 if(!empty($user_info)){
		 	 $where = array();
		 	 $where['type'] = PRODUCT_TYPE_3;//代金券
		 	 $where['price'] = 50;//代金券金额
			 $product_list = HttpDaoManager::getProductDao()->searchList($where,'',1);
			 $product_info = array();
			 if(!empty($product_list)){
			 	 $product_info = $product_list[0];
				 HttpServerManager::getTicketServer()->favourTicketSend($user_id, $product_info['id'], 1);//派发券
			 }
			 
			 //付费用户，给次卡
		 	 if($user_info['user_type']==USER_TYPE_MONEY){
		 	 		$user_class = $user_info['user_class']+2;//送2次
		 	 		if($user_info['user_class']>0){//有次卡
		 	 			$user_class_period_validity =strtotime("+ 5 day",$user_info['class_period_validity']);
		 	 		}else{
		 	 			$user_class_period_validity =strtotime("+ 5 day",strtotime(date('Y-m-d')));
		 	 		}
		 	 		$update_data = array();
		 	 		$update_data['user_class'] = $user_class;
		 	 		$update_data['class_period_validity'] = $user_class_period_validity;
					HttpDaoManager::getUserDao()->update($update_data, $user_id); 	 		
		 	 }
		 }
	}
	
	
	public function deleteBatchByid($id){
		if (is_array($id)){
			$id = implode(',',$id);
		}
		HttpDaoManager::getUserDao()->deleteBatchByid($id);
	}
	
	public function searchUserSends($where){
		if ($where['way'] ==MESSAGE_TYPE_EMAIL)		{
			$where['email'] = array('','<>');
		}
		if ($where['way']==MESSAGE_TYPE_MOBILE){
			$where['phone'] = array('','<>');
		}
		return  HttpDaoManager::getUserDao()->searchList($where);
	}
	public function userSend($where,$sendInfo){
		$userlist = self::searchUserSends($where);
		if ($where['way']==MESSAGE_TYPE_LETTER){
			$tmp= HttpServerManager::getLetterStationServer()->batchSend($userlist,$sendInfo);
		}
		else if($where['way']==MESSAGE_TYPE_EMAIL){
			$tmp=HttpServerManager::getEmailSendlistServer()->batchSend($userlist,$sendInfo);
		}
		else if($where['way']==MESSAGE_TYPE_MOBILE){
			
			$tmp=HttpServerManager::getMobileSendlistServer()->batchSend($userlist,$sendInfo);
		}
		return $tmp;
	}
	public function login($email,$password){
		$data = HttpDaoManager::getUserDao()->getByEmailByPassword($email, $password);
		if (empty($data)){
			return false;
		}
		else{
			$_SESSION['user'] = $data;
			HttpServerManager::getUserLoginLogServer()->add($data['english_name'], $data['id']);
			setcookie("COOKIE_LOGIN_NAME",$data['email'], time()+3600*24*90);
			return true;
		}
	}
	public function quit(){
		unset($_SESSION['user']);
	}
	public function userUpdate($data,$id){
		//用户更新QQ、SKYpe等相关信息
		//若用户依然具有未上的课，则更新相关信息
// 		$tmp = HttpDaoManager::getBookCourseDao()->getByUserId($id);
// 		if (!empty($tmp)){
// 			unset($data['skype_id']);
// 			unset($data['qq']);
// 		}
		if(isset($_SESSION['SMSCode'])&&!empty($_SESSION['SMSCode'])){
			if ($this->validationCode($data['phone'],$data['code'])===true){
				$data['real_phone'] =2;
			}else{
				if($_SESSION['SMSCode']!=$data['code']){
					return USER_ERROR_20;
				}
				if($_SESSION['SMS_PHONE']!=$data['phone']){
					return USER_ERROR_21;
				}
			}
		}
		HttpDaoManager::getUserDao()->update($data, $id);
		return true;
	}
	public function sendCode($phone){
// 		$tmp=HttpDaoManager::getUserDao()->get($userId);
// 		if (empty($tmp['phone'])){
// 			return USER_ERROR_9;
// 		}
		$code = rand(1000,9999);
		$content = '验证码：'.$code;
		HttpServerManager::getMobileSendlistServer()->sendSMS($phone,$content);
		$_SESSION['SMSCode'] = $code;
		$_SESSION['SMS_PHONE'] = $phone;
		
		$id = $_SESSION['user']['id'];
		$data = array();
		$data['phone'] = $phone;
		$data['sms_code'] =  $code;
		HttpDaoManager::getUserDao()->update($data, $id);
		
		return TRUE;
	}
	
	public function sendForgotCode($phone){
// 		$tmp=HttpDaoManager::getUserDao()->get($userId);
// 		if (empty($tmp['phone'])){
// 			return USER_ERROR_9;
// 		}
		$code = rand(1000,9999);
		$content = '验证码：'.$code;
		HttpServerManager::getMobileSendlistServer()->sendSMS($phone,$content);
		$_SESSION['forgotPasswordValidation']['code'] = $code;
		$_SESSION['forgotPasswordValidation']['phone'] = $phone;		
		
		return TRUE;
	}
	public function sendBookNoticeInfo($data){
		// 		$tmp=HttpDaoManager::getUserDao()->get($userId);
		// 		if (empty($tmp['phone'])){
		// 			return USER_ERROR_9;
		// 		}
		$code = rand(1000,9999);
		$book_date = $data['book_date_time'];
		$book_tool = $data['book_tool'];
		$content = "您好，您所预定的英语课堂将在'.$book_date.'开课,通讯工具为".$book_tool.",请做好相关准备,祝您听课愉快!";
		return HttpServerManager::getMobileSendlistServer()->sendSMS($phone,$content);;
	}	
	public function validationCode($phone,$code){
		if ($_SESSION['SMS_PHONE']==$phone&&$_SESSION['SMSCode']==$code){
			return true;
		}
	}
	public function getUserClassType($id){
		$userData = HttpDaoManager::getUserDao()->get($_SESSION['user']['id']);
 		if($userData['user_experience_class']==0){//体验课没了
	 		if($userData['class_period_validity']<time()&&$userData['monthly_class_period_validity']<time()){//均过期
	 			return USER_ERROR_ONE;
	 		}
 		}
		$userClass = array();
		$userClass2 = array();
		$userClassType = array('user_monthly_class','user_experience_class','user_class');
		$classTypeSpecial = 'user_experience_class';
		
		if($userData['user_monthly_class']>=1&&$userData['monthly_class_period_validity']>=time()){
				$userClass[] = $userClassType[0];
				$userClass2[] = $userClassType[0];
		}
		if($userData['user_experience_class']>=1){
				$userClass[] = $userClassType[1];
				$userClass2[] = $userClassType[1];
		}
		if($userData['user_class']>=1&&$userData['class_period_validity']>=time()){
				$userClass[] = $userClassType[2];
				$userClass2[] = $userClassType[2];
		}
		
//			if ($userData[$v]>=1){
//				$userClass[] = $v;
//// 				if ($v != $classTypeSpecial){
//					$userClass2[] = $v;
//// 				}
//			
//			}
		
		if (empty($userClass)){
			return USER_ERROR_ONE;
		}
		else{
			if (empty($userClass2)){
				return array('classType'=>$classTypeSpecial,'classTypeSpecial'=>1);
			}
			else{
				return array('classType' =>$userClass2,'classTypeSpecial'=>0);
			}
		}
	}
	public function updatePassword($email,$oldPassword,$newPassword){
		$userDao = HttpDaoManager::getUserDao();
		$data = $userDao->getByEmailByPassword($email, $oldPassword);
		if (empty($data)){
			return  USER_ERROR_8;
		}
		$userDao->updateByEmail(array('password'=>md5($newPassword)), $email);
		return true;
	}
	public function overdueEmpty(){//清除过期用户的账户信息
		$userDao = HttpDaoManager::getUserDao();
		$expire_time = strtotime(date('Y-m-d'));
		$filter = array();
		$filter['get_expire_user_class'] = 1;
		$filter['expire_time'] = $expire_time;
		$users = $userDao->searchList($filter);
		$tmp = array();
		$time = time();
		$userIdArray = array();
		foreach ($users as $v){//次卡人员
			$userIdArray[] = $v['id'];
			$tmp[] = array(
				'user_id'         => $v['id'],
				'class'           => $v['user_class'],
				'type'            => PRODUCT_TYPE_2,
				'time'            =>  $time,
				'period_validity' => $v['class_period_validity']
			);
		}
		
		if (!empty($userIdArray)){
			$userDao->updateInId(array('user_class'=>0,'class_period_validity'=>0), $userIdArray);
		}

		$filter = array();
		$filter['get_expire_user_monthly_class'] = 1;
		$filter['expire_time'] = $expire_time;
		$users = $userDao->searchList($filter);		
		$userIdArray = array();
		foreach ($users as $v){
			$userIdArray[] = $v['id'];
			$tmp[] = array(
				'user_id'         => $v['id'],
				'class'           => $v['user_monthly_class'],
				'type'            => PRODUCT_TYPE_1,
				'time'            =>  $time,
				'period_validity' => $v['monthly_class_period_validity']
			);
		}
		if (!empty($userIdArray)){
			$userDao->updateInId(array('user_monthly_class'=>0,'monthly_class_period_validity'=>0), $userIdArray);
		}
		$userOverdueEmptyDao = HttpDaoManager::getUserOverdueEmptyDao();
		if (!empty($tmp)){
			$userOverdueEmptyDao->addArray($tmp);
		}
	}
	public function customSMS($userId){
		HttpDaoManager::getUserDao()->update(array('sms_server'=>1), $userId);
	}
	public function notCustomSMS($userId){
		HttpDaoManager::getUserDao()->update(array('sms_server'=>2), $userId);
	}
	public function updateIntegral($data){
		$userDao = HttpDaoManager::getUserDao();
		$userData  = $userDao->get($data['user_id']);
		$integral=$userData['integral'] + $data['integral'];
		if ($integral>=0){
			$data['time'] = time();
			HttpDaoManager::getUserIntegralLogDao()->add($data);
			$userDao->update(array('integral'=>$integral), $data['user_id']);
			return true;
		}
		else{
			return USER_ERROR_16;
		}
	}
	
	public function changeUserMoney($user_id,$money_add){
		$user_info = HttpDaoManager::getUserDao()->get($user_id);
		if(!empty($user_info)){
			$user_money = $user_info['user_moeny'];
			$user_add_money = $user_money+$money_add;
			$new_user_info = array();
			$new_user_info['user_moeny'] =$user_add_money; 
			HttpDaoManager::getUserDao()->update($new_user_info, $user_id);//更新余额信息
			$userMoneyLogInfo = array();
			$userMoneyLogInfo['type'] = USER_LOG_MONEY;
			$userMoneyLogInfo['money'] = $money_add;
			$userMoneyLogInfo['time'] = time();
			$userMoneyLogInfo['add_user'] = $_SESSION['user']['english_name'];
			$userMoneyLogInfo['user_id'] = $_SESSION['user']['id'];
			$userMoneyLogInfo['content'] = '充值';
			HttpDaoManager::getUserMoneyLogDao()->add($userMoneyLogInfo);
		}
		
	}
	
	public function changeUserAccount($user_id,$product,$ticket_log_info){
			$type = $product['type'];
			$user_info = HttpDaoManager::getUserDao()->get($_SESSION['user']['id']);
			$user_money = $user_info['user_moeny'];
			$user_class = $user_info['user_class'];
			$user_monthly_class= $user_info['user_monthly_class'];
			$user_id = $user_info['id'];
		
			if($type==PRODUCT_TYPE_5){
				$user_card_info = array();
				$user_card_info['user_moeny'] = $user_money+$product['price'];
				$user_card_info['user_id']= $user_id;
		
				HttpDaoManager::getUserDao()->update($user_card_info,$user_id);		
								
		 		$user_money_log = array();
		 		$user_money_log['type']  = USER_LOG_CARD;
		 		$user_money_log['money'] = $product['price'];
		 		$user_money_log['time'] = time();
		 		$user_money_log['add_user'] = $_SESSION['user']['english_name']; 
		 		$user_money_log['user_id'] = $_SESSION['user']['id']; 
		 		$user_money_log_type = Common::_t('user_money_log_type');
		 		$user_money_log['content'] =$user_money_log_type[USER_LOG_CARD];
				HttpDaoManager::getUserMoneyLogDao()->add($user_money_log);
			}
		
			if($type==PRODUCT_TYPE_4){
				$class_period_validity = $user_info['class_period_validity'];
				$period_validity = $product['period_validity'];
				if($class_period_validity>time()){
					$class_period_validity = strtotime("+" . $period_validity . " day ", $class_period_validity);
				}else{
					$class_period_validity = strtotime("+" . $period_validity . " day ", time());
				}
				$user_card_info = array();
				$user_card_info['user_class'] = $user_class+$product['lesson'];
				$user_card_info['user_id']= $user_id;
				$user_card_info['class_period_validity']=$class_period_validity;				
				HttpDaoManager::getUserDao()->update($user_card_info,$user_id);		
								
				$user_class_hour_log_type = Common::_t('user_class_hour_log_type');
				$tmp = array(
						'type'       => USER_CLASS_HOUR_LOG_4,
						'class_type' => BOOK_TYPE_1,//
						'target_id'  => $ticket_log_info['id'],//是否保存于pay_log
						'class_hour' => $product['lesson'],
						'user_id'    => $_SESSION['user']['id'],
						'add_user'   => $_SESSION['user']['english_name'],
						'remark'     => $user_class_hour_log_type[USER_CLASS_HOUR_LOG_4]
				);
				HttpServerManager::getUserClassHourLogServer()->add($tmp);
			}
		
			if($type==PRODUCT_TYPE_7){
				$monthly_class_period_validity = $user_info['monthly_class_period_validity'];
				$period_validity = $product['period_validity'];
				if($class_period_validity>time()){
					$monthly_class_period_validity = strtotime("+" . $period_validity . " day ", $monthly_class_period_validity);
				}else{
					$monthly_class_period_validity = strtotime("+" . $period_validity . " day ", time());
				}
				$user_card_info = array();
				$user_card_info['user_monthly_class'] = $user_monthly_class+$product['lesson'];
				$user_card_info['user_id']= $user_id;
				$user_card_info['monthly_class_period_validity']=$monthly_class_period_validity;				
				HttpDaoManager::getUserDao()->update($user_card_info,$user_id);		

								
				$user_class_hour_log_type = Common::_t('user_class_hour_log_type');
				$tmp = array(
						'type'       => USER_CLASS_HOUR_LOG_5,
						'class_type' => BOOK_TYPE_3,//
						'target_id'  => $ticket_log_info['id'],//是否保存于pay_log
						'class_hour' => $product['lesson'],
						'user_id'    => $_SESSION['user']['id'],
						'add_user'   => $_SESSION['user']['english_name'],
						'remark'     => $user_class_hour_log_type[USER_CLASS_HOUR_LOG_5]
				);
				
				HttpServerManager::getUserClassHourLogServer()->add($tmp);		
			}
	}
	
	function exchange($id,$userId){
		$sql =  ClassManager::getSql();
		$sql->preareStart();
		$productData  = HttpDaoManager::getProductDao()->get($id);
		$integral = $productData['price']*10;
		$data=array(
			'integral'=>-$integral,
			'type' => INTEGRAL_TYPE_3,
			'user_id' =>$userId
		);
		$tmp =  HttpServerManager::getUserServer()->updateIntegral($data);
		if ($tmp===true){
			$tmpa = HttpServerManager::getTicketServer()->exchange($id, $userId);
			if ($tmpa===true){
				$sql->preareEnd();
			}
			return $tmpa;
		}
		return $tmp;
	}
	public function sendVerification($email){
		$data = HttpDaoManager::getUserDao()->searchList(array('email'=>$email));
		if (empty($data)){
			return USER_ERROR_18;
		}
		else{
			$code = rand(10000, 99999);
			$_SESSION['forgotPasswordValidation']['code'] = $code;
			$_SESSION['forgotPasswordValidation']['email'] = $email;
			HttpServerManager::getEmailSendlistServer()->sendEmail($email, '找回密码验证码', '您的验证码：'.$code);
			return true;
		}
	}
	
	public function bindUserAndQQ($user_id,$qq_user_id){
		$userQQInfo = HttpDaoManager::getUserDao()->get($qq_user_id);	
		$userEmailInfo = HttpDaoManager::getUserDao()->get($user_id);
		if(!empty($userQQInfo)&&!empty($userEmailInfo)){
			$phone = $userQQInfo['phone'];
			$qq = $userQQInfo['qq'];
			$password = $userQQInfo['password'];
			$email_phone  = $userEmailInfo['phone'];
			$email_qq = $userEmailInfo['qq'];
			$email_password = $userEmailInfo['password'];
			if(!empty($email_phone)){
				$phone = $email_phone;
			}
			if(!empty($email_qq)){
				$qq = $email_qq;
			}
			if(!empty($email_password)){
				$password = $email_password;
			}
			
			$userInfo = array(); 
			$userInfo['qq'] = $qq; 
			$userInfo['qq_bind_status'] = QQ_BIND_SUCCESS; 
			$userInfo['qq_bind_id'] = $qq_user_id; 
			$userInfo['phone'] = $phone;
			$userInfo['password'] = $password;
			$userInfo['openid'] = $userQQInfo['openid'];
			$userInfo['nickname'] = $userQQInfo['nickname'];
			HttpDaoManager::getUserDao()->update($userInfo, $user_id);
 			HttpDaoManager::getUserDao()->deleteBatchByid($qq_user_id);
			$_SESSION['user'] = $userEmailInfo;
			return true;
		}
		return false;
						
	}
	
	public function forgotPassword($data){
		if ($_SESSION['forgotPasswordValidation']['code']==$data['code']){
			if($data['code_way']=='phone'){
				HttpDaoManager::getUserDao()->updateByPhone(array('password'=>md5($data['password'])), $_SESSION['forgotPasswordValidation']['phone']);
				unset($_SESSION['forgotPasswordValidation']);
				return true;				
			}
			if($data['code_way']=='email'){
				HttpDaoManager::getUserDao()->updateByEmail(array('password'=>md5($data['password'])), $_SESSION['forgotPasswordValidation']['email']);
				unset($_SESSION['forgotPasswordValidation']);
				return true;
			}
		}
		return false;
	}
	
	public function getUserName(){
		$user_name ="";
		if(empty($_SESSION['user']['openid'])){//openId用户存在，则为QQ用户
		    if($_SESSION['user']['english_name']!=""){
	        	$user_name = $_SESSION['user']['english_name'];
	        }else{	
	        	if(!empty($_SESSION['user']['email'])){
	        		$user_name = substr($_SESSION['user']['email'],0,stripos($_SESSION['user']['email'],'@'));
	        	}
	        }
		}else{
        	$user_name = $_SESSION['user']['nickname'];
		}
		
        return $user_name;
	}
	
	public function validateUserActiveKind($userInfo){
		$userActiveArray = array(USER_KIND_ACTIVE_515,
				USER_KIND_ACTIVE_2014SUMMER_1,
				USER_KIND_ACTIVE_2014SUMMER_2,
				USER_KIND_ACTIVE_2014SUMMER_3,
				USER_KIND_ACTIVE_2014SUMMER_4,
				USER_KIND_ACTIVE_2014SUMMER_5,
				USER_KIND_ACTIVE_2014SUMMER_6);
		if(in_array($userInfo['user_kind'],$userActiveArray)){
			return true;
		}
		return false;
	}
}
?>